package com.egoo.ticket.server.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.dao.WorkOrderDao;
import com.egoo.ticket.server.dao.WorkOrderTypeNodeDao;
import com.egoo.ticket.server.pojo.dto.FormTemplateInputDto;
import com.egoo.ticket.server.pojo.dto.PageOutputDto;
import com.egoo.ticket.server.pojo.dto.SelectByNameAndTypeDto;
import com.egoo.ticket.server.pojo.entity.FormTemplate;
import com.egoo.ticket.server.service.CustomFieldService;
import com.egoo.ticket.server.service.FormTemplateService;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Donny_Dong
 */
@RestController
@Slf4j
@RequestMapping(value = "/v1/formTemplate", produces = "application/json")
@Api(value = "模板管理",tags = "模板管理",description = "自定义模板管理")
public class FormTemplateController {

	@Autowired
	private CustomFieldService customFieldService;
	@Autowired
	private FormTemplateService formTemplateService;
	@Autowired
	private WorkOrderTypeNodeDao workOrderTypeNodeDao;
	@Autowired
	private WorkOrderDao workOrderDao;

	@ApiOperation(value = "新建表单模板", notes = "新建表单模板")
	@RequestMapping(method = RequestMethod.POST, value="/create")
	public DbResponse createCustomfield(@ApiParam(value="create", required=true) @RequestBody FormTemplateInputDto formTemplateInputDto,
										HttpServletRequest request){
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "新建失败");
		String name = formTemplateInputDto.getName();
		if(StringUtils.isBlank(name) || null == name){
			dbResponse.setMsg("模板名称不能为空");
			return dbResponse;
		}else {
			if(name.length()> ConstantCode.ControllerStrLengthCheck.LENGTH){
				dbResponse.setMsg("模板名称不能超过20个字");
				return dbResponse;
			}
		}
		//根据name查询是否有该模板
		FormTemplate formTemplate = formTemplateService.selectByEqualsName(name,tenantId);
		if (formTemplate != null){
			dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
			dbResponse.setMsg(name + "已存在");
			return dbResponse;
		}
		formTemplateInputDto.setTenantId(tenantId);
		Integer retCode = formTemplateService.create(formTemplateInputDto);

		dbResponse.setRetCode(200);
		dbResponse.setMsg("新建成功");

		return dbResponse;
	}

	@ApiOperation(value = "根据id获取模板的属性内容", notes = "根据id获取模板的属性内容")
	@RequestMapping(method = RequestMethod.GET, value="/selectContentById")

	public DbResponse copyById(@ApiParam(value="id", required=true) @RequestParam(name = "id") Integer id,
							   HttpServletRequest request){
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		Map<String, Object> hashMap = new HashMap<>(4);
		hashMap.put("formTemplateId",id);
		hashMap.put("tenantId",tenantId);
//		List<WorkOrderTypeNodeVo> workOrderTypeNodeVos = workOrderTypeNodeDao.selectNodeListByCondition(hashMap);
//
//		Integer integer = getNoCloseWorkOrderWithTemplate(hashMap, workOrderTypeNodeVos);
//		if (0 < integer){
//			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"该模板有"+integer+"条工单未流转完成");
//		}
		FormTemplate formTemplate = formTemplateService.selectContentById(id);
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,"获取成功",formTemplate);
	}

//	/**
//	 * @Author: Donny_dong
//	 * @Description: 获取未流转完的工单数
//	 * @Param:
//	 * @return:
//	 * @Date: 2020/3/26
//	 */
//	private Integer getNoCloseWorkOrderWithTemplate(Map<String, Object> hashMap, List<WorkOrderTypeNodeVo> workOrderTypeNodeVos) {
//		Integer integer = 0;
//		Set<Long> workOrderTypeIdList = workOrderTypeNodeVos.stream().map(workOrderTypeNodeVo -> workOrderTypeNodeVo.getWorkOrderTypeId()).collect(Collectors.toSet());
//		for (Long workOrderTypeId:workOrderTypeIdList ) {
//			 integer += workOrderDao.selectTotalNotCloseStatus(workOrderTypeId);
//		}
//		return integer;
//	}


	@ApiOperation(value = "根据id获取getById", notes = "根据id获取getById")
	@RequestMapping(method = RequestMethod.GET, value="/getById")

	public DbResponse getById(@ApiParam(value="id", required=true) @RequestParam(name = "id") Integer id){
		DbResponse dbResponse = new DbResponse();
		FormTemplate formTemplate = formTemplateService.selectContentById(id);
		JSONObject formTemplateContent = formTemplate.getContent();
		JSONArray list = formTemplateContent.getJSONArray("list");
		for(int i = 0;i<list.size();i++){
			Boolean tag = list.getJSONObject(i).getJSONObject("options").getBoolean("required");
		}
		dbResponse.setRetCode(200);
		dbResponse.setData(formTemplate);
		return dbResponse;
	}

	@ApiOperation(value = "根据id复制表单模板", notes = "根据id复制表单模板")
	@RequestMapping(method = RequestMethod.GET, value="/copyById")
	public DbResponse selectContentById(@ApiParam(value="id", required=true) @RequestParam(name = "id") Integer id){
		DbResponse dbResponse = new DbResponse();
		FormTemplate formTemplate = formTemplateService.selectContentById(id);
		String name = formTemplate.getName();
		name = name + "copy";
		formTemplate.setName(name);
		dbResponse.setRetCode(200);
		dbResponse.setData(formTemplate);
		return dbResponse;
	}

	@ApiOperation(value = "获取所有的表单模板", notes = "获取所有的表单模板")
	@RequestMapping(method = RequestMethod.GET, value="/selectAll")
	public DbResponse selectAll(@ApiParam(value = "当前页", required = true) @RequestParam("currentPage") Integer currentPage,
								@ApiParam(value = "每页行数", required = true) @RequestParam("pageSize") Integer pageSize,
								HttpServletRequest request){
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse();
		PageOutputDto pageOutputDto = formTemplateService.selectAll(currentPage, pageSize,tenantId);
		dbResponse.setRetCode(200);
		dbResponse.setData(pageOutputDto);
		return dbResponse;
	}
	
	@ApiOperation(value = "根据工单类型节点id获取模板信息", notes = "根据工单类型节点id获取模板信息")
	@RequestMapping(method = RequestMethod.GET, value="/getTemplateInfoByTypeNodeId")
	public DbResponse selectAll(@ApiParam(value = "工单类型节点id", required = true) @RequestParam("typeNodeId") String typeNodeId){
		if (StringUtils.isEmpty(typeNodeId)) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"工单类型节点id不能为空！");
		}
		try {
			FormTemplate formTemplate = formTemplateService.getFormTemplateByTypeNodeId(typeNodeId);
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.SELECT_SUCCESS_MSG, formTemplate);
		} catch (Exception e) {
			log.info("根据工单类型节点id获取模板信息异常"+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"根据工单类型节点id获取模板信息异常");
		}
	}
	
	@ApiOperation(value = "根据模板名称获取表单模板", notes = "根据模板名称获取表单模板")
	@RequestMapping(method = RequestMethod.POST, value="/selectByName")
	public DbResponse selectByNameAndType(@ApiParam(value="selectByName", required=true) @RequestBody SelectByNameAndTypeDto selectByNameAndTypeDto,
										  HttpServletRequest request){
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		String name = selectByNameAndTypeDto.getName();
		Integer currentPage = selectByNameAndTypeDto.getCurrentPage();
		Integer pageSize = selectByNameAndTypeDto.getPageSize();
		DbResponse dbResponse = new DbResponse();
		PageOutputDto pageOutputDto = formTemplateService.selectByName(name, currentPage, pageSize,tenantId);
		if(0 == pageOutputDto.getList().size()){
			pageOutputDto = formTemplateService.selectByName(name, 1, pageSize,tenantId);
		}
		dbResponse.setRetCode(200);
		dbResponse.setData(pageOutputDto);
		return dbResponse;
	}

	@ApiOperation(value = "更新表单模板的属性", notes = "更新表单模板的属性")
	@RequestMapping(method = RequestMethod.POST, value="/updateContent")
	public DbResponse updateContent(@ApiParam(value="formTemplateInputDto", required=true) @RequestBody FormTemplateInputDto formTemplateInputDto,
									HttpServletRequest request){
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "更新失败");
		Integer id = formTemplateInputDto.getId();
		FormTemplate formTemplate = formTemplateService.selectById(id);
		if (formTemplate== null){
			dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
			dbResponse.setMsg("该表单模板不存在");
			return dbResponse;
		}
		String name = formTemplateInputDto.getName();
		if(StringUtils.isBlank(name) || null == name){
			dbResponse.setMsg("模板名称不能为空");
			return dbResponse;
		}else {
			if(name.length()> ConstantCode.ControllerStrLengthCheck.LENGTH){
				dbResponse.setMsg("模板名称不能超过80个字");
				return dbResponse;
			}
			formTemplate = formTemplateService.selectByEqualsName(name, tenantId);
			if (formTemplate !=null && !id.equals(formTemplate.getId())){
				dbResponse.setMsg("模板名称已存在");
				return dbResponse;
			}
		}
		Integer retCode = formTemplateService.updateContent(formTemplateInputDto);
		if (retCode == 1) {
			dbResponse.setRetCode(200);
			dbResponse.setMsg("更新成功");
		}
		return dbResponse;
	}

	@ApiOperation(value = "删除表单模板", notes = "删除表单模板")
	@RequestMapping(method = RequestMethod.GET, value="/delete")
	public DbResponse delete(@ApiParam(value="id", required=true) @RequestParam(name = "id") Integer id,
							 HttpServletRequest request){
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		FormTemplate formTemplate = formTemplateService.selectById(id);
		if (formTemplate== null){
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"该表单模板不存在");
		}
//		Map<String, Object> hashMap = new HashMap<>(4);
//		hashMap.put("formTemplateId",id);
//		hashMap.put("tenantId",tenantId);
//		List<WorkOrderTypeNodeVo> workOrderTypeNodeVos = workOrderTypeNodeDao.selectNodeListByCondition(hashMap);
//		if (0 != workOrderTypeNodeVos.size()){
//			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"该模板有"+workOrderTypeNodeVos.size()+"条节点使用记录时");
//		}
		Integer retCode = formTemplateService.delete(formTemplate);
		if (retCode == 1) {
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,"删除成功");
			}
		return new DbResponse(ResponseConstant.RES_FAIL_CODE,"删除失败");
	}

	@ApiOperation(value = "批量删除表单模板", notes = "批量删除表单模板")
	@RequestMapping(method = RequestMethod.POST, value="/deleteBatch")
	public DbResponse deleteBatch (@RequestBody List<Integer> idList,
								   HttpServletRequest request){
//		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
//		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "删除失败");
		List<FormTemplate> formTemplateList = new ArrayList<>();
		for (Integer id:idList){
//			FormTemplate formTemplate = formTemplateService.selectById(id);
//			if (formTemplate== null){
//				dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
//				dbResponse.setMsg("该表单模板不存在");
//				return dbResponse;
//			}
//			Integer useStatus = formTemplate.getUseStatus();
//			String name = formTemplate.getName();
//			Map<String, Object> hashMap = new HashMap<>(4);
//			hashMap.put("formTemplateId",id);
//			hashMap.put("tenantId",tenantId);
//			List<WorkOrderTypeNodeVo> workOrderTypeNodeVos = workOrderTypeNodeDao.selectNodeListByCondition(hashMap);
//			if (workOrderTypeNodeVos.size() > 0){
//				dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
//				dbResponse.setMsg("有"+workOrderTypeNodeVos.size()+"条工单类型正在使用该模板");
//				return dbResponse;
//			}
			FormTemplate formTemplate = new FormTemplate();
			formTemplate.setId(id);
			formTemplateList.add(formTemplate);
		}
		 formTemplateService.deleteBatch(formTemplateList);
		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,
				ResponseConstant.DEL_SUCCESS_MSG);
	}
}
